<template>
  <div class="chat-component">
    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messagesContainer">
      <div 
        v-for="(message, index) in messages" 
        :key="index"
        :class="['message-wrapper', message.role === 'user' ? 'user-message' : 'ai-message']"
      >
        <div class="message-content">
          <!-- 头像 -->
          <div class="avatar">
            <span v-if="message.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          
          <div class="message-right">
            <!-- 消息内容 -->
            <div class="message-bubble">
              <!-- 文本内容 (Markdown渲染) -->
              <div 
                class="message-text markdown-body" 
                v-html="renderMarkdown(message.content)"
              ></div>
              
              <!-- 图片列表 -->
              <div v-if="message.images && message.images.length > 0" class="message-images">
                <div 
                  v-for="(image, imgIndex) in message.images" 
                  :key="imgIndex"
                  class="image-item"
                >
                  <img :src="image" :alt="`图片${imgIndex + 1}`" @click="previewImage(image)">
                </div>
              </div>
              
              <!-- 文件列表 -->
              <div v-if="message.files && message.files.length > 0" class="message-files">
                <div 
                  v-for="(file, fileIndex) in message.files" 
                  :key="fileIndex"
                  class="file-item"
                >
                  <span class="file-icon">📄</span>
                  <div class="file-info">
                    <div class="file-name">{{ file.name }}</div>
                    <div class="file-size">{{ formatFileSize(file.size) }}</div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 消息底部信息：时间 + 操作按钮 -->
            <div class="message-footer">
              <!-- 时间戳 -->
              <div class="message-time">{{ message.timestamp }}</div>
              
              <!-- AI消息操作按钮 -->
              <div v-if="message.role === 'ai'" class="message-actions">
                <button 
                  class="action-btn copy-btn" 
                  @click="copyMessage(message.content)"
                  :title="copiedIndex === index ? '已复制' : '复制'"
                >
                  <span v-if="copiedIndex === index">✓</span>
                  <span v-else>📋</span>
                  <span class="btn-text">{{ copiedIndex === index ? '已复制' : '复制' }}</span>
                </button>
                <button 
                  v-if="index === messages.length - 1 && !isAiTyping"
                  class="action-btn regenerate-btn" 
                  @click="regenerateResponse(index)"
                  title="重新生成"
                >
                  <span>🔄</span>
                  <span class="btn-text">重新生成</span>
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- AI正在输入提示 -->
      <div v-if="isAiTyping" class="message-wrapper ai-message">
        <div class="message-content">
          <div class="avatar">🤖</div>
          <div class="message-bubble typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">
      <!-- 已选择的附件预览 -->
      <div v-if="enableMultimodal && selectedFiles.length > 0" class="selected-files-preview">
        <div 
          v-for="(file, index) in selectedFiles" 
          :key="index"
          class="preview-file-item"
          :class="{'is-image': file.isImage}"
        >
          <!-- 图片预览 -->
          <img v-if="file.isImage" :src="file.preview" :alt="file.name">
          
          <!-- 文件图标 -->
          <div v-else class="file-icon-wrapper">
            <span class="file-icon">📄</span>
            <span class="file-name">{{ file.name }}</span>
            <span class="file-size">{{ formatFileSize(file.size) }}</span>
          </div>
          
          <!-- 删除按钮 -->
          <button class="remove-file-btn" @click="removeFile(index)" title="删除附件">
            ✕
          </button>
        </div>
      </div>

      <!-- 输入框和按钮 -->
      <div class="input-controls">
        <!-- 上传按钮 -->
        <label v-if="enableMultimodal" class="upload-btn" title="上传附件">
          <input 
            type="file" 
            @change="handleFileSelect"
            accept="image/*,.pdf,.doc,.docx,.txt,.xlsx,.xls,.ppt,.pptx"
            multiple
            ref="fileInput"
          >
          <span>📎</span>
        </label>

        <!-- 图片合并按钮 -->
        <button 
          v-if="enableMultimodal"
          class="merge-images-btn" 
          @click="openMergeModal"
          title="图片合并工具"
        >
          🖼️
        </button>

        <!-- 文本输入框 -->
        <textarea
          v-model="inputMessage"
          @keydown.enter.exact.prevent="sendMessage"
          @keydown.ctrl.enter.exact="inputMessage += '\n'"
          placeholder="输入消息... (Enter发送, Ctrl+Enter换行)"
          rows="1"
          ref="textarea"
        ></textarea>

        <!-- 发送按钮 -->
        <button 
          v-if="!isAiTyping"
          class="send-btn" 
          @click="sendMessage"
          :disabled="!canSend"
        >
          发送
        </button>
        
        <!-- 停止按钮 -->
        <button 
          v-else
          class="stop-btn" 
          @click="stopAIResponse"
        >
          停止
        </button>
      </div>
    </div>

    <!-- 图片预览模态框 -->
    <div v-if="previewImageUrl" class="image-preview-modal" @click="closePreview">
      <div class="preview-content">
        <img :src="previewImageUrl" alt="预览">
        <button class="close-preview-btn">✕</button>
      </div>
    </div>

    <!-- 图片合并弹框 -->
    <div v-if="showMergeModal" class="merge-modal" @click="closeMergeModal">
      <div class="merge-modal-content" @click.stop>
        <div class="modal-header">
          <h3>图片合并工具</h3>
          <button class="close-btn" @click="closeMergeModal">×</button>
        </div>
        
        <div class="modal-body">
          <!-- 上传区域 -->
          <div class="upload-section">
            <label class="upload-btn-large" :class="{ 'disabled': uploadedImages.length >= 4 }">
              <input 
                type="file" 
                @change="handleImageUpload" 
                accept="image/*" 
                multiple
                :disabled="uploadedImages.length >= 4"
              >
              <span>📁</span>
              <span>上传图片 (最多4张)</span>
            </label>
            
            <div class="upload-info">
              已上传 {{ uploadedImages.length }}/4 张图片
            </div>
          </div>
          
          <!-- 图片预览区域 -->
          <div v-if="uploadedImages.length > 0" class="preview-section">
            <h4>图片预览</h4>
            <div class="image-previews">
              <div 
                v-for="(image, index) in uploadedImages" 
                :key="index"
                class="preview-item"
              >
                <img :src="image.data" :alt="'图片' + (index + 1)">
                <div class="image-info">
                  <span class="image-number">{{ index + 1 }}</span>
                  <button class="remove-btn" @click="removeImage(index)">×</button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 合并结果预览 -->
          <div v-if="mergedImage" class="result-section">
            <h4>合并结果</h4>
            <div class="result-preview">
              <img :src="mergedImage" alt="合并后的图片">
            </div>
          </div>
        </div>
        
        <div class="modal-footer">
          <button 
            class="merge-btn" 
            @click="mergeImages" 
            :disabled="uploadedImages.length < 2"
          >
            合并图片
          </button>
          <button 
            v-if="mergedImage" 
            class="download-btn" 
            @click="downloadMergedImage"
          >
            下载合并图片
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { marked } from 'marked'
import { sendChatStream } from '@/services/chatApi'

export default {
  name: 'ChatComponent',
  props: {
    // 图片列表 (已废弃，保留兼容性)
    initialImages: {
      type: Array,
      default: () => []
    },
    // 是否支持多模态 (文件上传)
    enableMultimodal: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      messages: [],
      inputMessage: '',
      isAiTyping: false,
      previewImageUrl: null,
      currentRequest: null, // 当前正在进行的请求
      currentAiMessage: '', // 当前AI正在输出的消息
      copiedIndex: null, // 已复制的消息索引
      copyTimer: null, // 复制状态定时器
      selectedFiles: [], // 选中的附件列表
      showMergeModal: false, // 控制图片合并弹框显示
      uploadedImages: [], // 已上传的图片数组
      mergedImage: null // 合并后的图片base64数据
    }
  },
  computed: {
    canSend() {
      if (this.enableMultimodal) {
        return this.inputMessage.trim() || this.selectedFiles.length > 0
      }
      return this.inputMessage.trim()
    }
  },
  mounted() {
    // 配置marked选项
    marked.setOptions({
      breaks: true, // 支持GitHub风格的换行
      gfm: true, // 启用GitHub风格的Markdown
      headerIds: false,
      mangle: false
    })
  },
  methods: {
    // 添加消息
    addMessage(message) {
      this.messages.push({
        ...message,
        timestamp: this.getCurrentTime()
      })
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 发送消息
    sendMessage() {
      if (!this.canSend) return

      // 构建当前消息内容
      const content = []
      const messageImages = []
      const messageFiles = []
      
      // 添加文本内容
      if (this.inputMessage.trim()) {
        content.push({
          type: 'text',
          text: this.inputMessage.trim()
        })
      }
      
      // 添加附件内容 (仅在多模态模式下)
      if (this.enableMultimodal) {
        this.selectedFiles.forEach(file => {
          if (file.isImage) {
            // 图片类型
            content.push({
              type: 'image_url',
              image_url: {
                url: file.preview
              }
            })
            messageImages.push(file.preview)
          } else {
            // 其他文件类型
            content.push({
              type: 'file',
              file: {
                name: file.name,
                type: file.type,
                size: file.size,
                url: file.preview // 实际项目中需要上传到服务器获取URL
              }
            })
            messageFiles.push({
              name: file.name,
              type: file.type,
              size: file.size,
              url: file.preview
            })
          }
        })
      }

      const userMessage = {
        role: 'user',
        content: this.inputMessage.trim() || '',
        images: messageImages,
        files: messageFiles
      }

      // 添加用户消息到界面
      this.addMessage(userMessage)

      // 清空输入和附件
      this.inputMessage = ''
      if (this.enableMultimodal) {
        this.selectedFiles = []
        if (this.$refs.fileInput) {
          this.$refs.fileInput.value = ''
        }
      }

      // 构建完整的历史聊天记录
      const historyMessages = this.buildHistoryMessages()
      
      // 构建符合API格式的聊天参数
      const chatParams = {
        model: 'zrt-multimodal-llm-8b',
        messages: historyMessages
      }

      // 触发事件传递给父组件
      this.$emit('send-message', {
        text: userMessage.content,
        images: messageImages,
        files: messageFiles,
        chatParams: chatParams
      })

      // 打印调试信息
      console.log('聊天参数(包含历史记录):', JSON.stringify(chatParams, null, 2))

      // 调用真实AI接口
      this.sendAIRequest(chatParams)
    },

    // 构建历史聊天记录(转换为API格式)
    buildHistoryMessages() {
      const apiMessages = []
      
      this.messages.forEach(msg => {
        if (msg.role === 'user') {
          // 用户消息: 构建 content 数组
          const content = []
          
          // 添加文本
          if (msg.content) {
            content.push({
              type: 'text',
              text: msg.content
            })
          }
          
          // 添加图片
          if (msg.images && msg.images.length > 0) {
            msg.images.forEach(imageUrl => {
              content.push({
                type: 'image_url',
                image_url: {
                  url: imageUrl
                }
              })
            })
          }
          
          // 添加其他文件
          if (msg.files && msg.files.length > 0) {
            msg.files.forEach(file => {
              content.push({
                type: 'file',
                file: file
              })
            })
          }
          
          apiMessages.push({
            role: 'user',
            content: content
          })
        } else if (msg.role === 'ai') {
          // AI消息: 直接使用文本内容
          apiMessages.push({
            role: 'assistant',
            content: msg.content || ''
          })
        }
      })
      
      return apiMessages
    },

    // 发送AI请求(流式)
    sendAIRequest(chatParams) {
      this.isAiTyping = true
      this.currentAiMessage = ''
      
      // 取消之前的请求(如果存在)
      if (this.currentRequest) {
        this.currentRequest.abort()
      }

      // 发送流式请求
      this.currentRequest = sendChatStream(
        chatParams,
        // onMessage: 接收到消息片段
        (content) => {
          this.currentAiMessage += content
          
          // 更新或添加AI消息
          this.updateAIMessage(this.currentAiMessage)
        },
        // onComplete: 流式响应完成
        () => {
          this.isAiTyping = false
          this.currentRequest = null
          console.log('AI回复完成')
        },
        // onError: 发生错误
        (error) => {
          this.isAiTyping = false
          this.currentRequest = null
          console.error('AI请求失败:', error)
          
          // 显示错误消息
          this.addMessage({
            role: 'ai',
            content: '抱歉,发生了错误,请稍后重试。错误信息: ' + error.message
          })
        }
      )
    },

    // 更新AI消息(流式输出时)
    updateAIMessage(content) {
      // 查找最后一条AI消息
      const lastMessage = this.messages[this.messages.length - 1]
      
      if (lastMessage && lastMessage.role === 'ai' && this.isAiTyping) {
        // 更新现有消息
        lastMessage.content = content
        lastMessage.timestamp = this.getCurrentTime()
      } else {
        // 添加新消息
        this.addMessage({
          role: 'ai',
          content: content
        })
      }
      
      this.$nextTick(() => {
        this.scrollToBottom()
      })
    },

    // 停止AI回复
    stopAIResponse() {
      if (this.currentRequest) {
        this.currentRequest.abort()
        this.currentRequest = null
        this.isAiTyping = false
      }
    },

    // 预览图片
    previewImage(url) {
      this.previewImageUrl = url
    },

    // 关闭预览
    closePreview() {
      this.previewImageUrl = null
    },

    // 滚动到底部
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },

    // 获取当前时间
    getCurrentTime() {
      const now = new Date()
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      return `${hours}:${minutes}`
    },

    // 渲染Markdown内容
    renderMarkdown(content) {
      if (!content) return ''
      return marked.parse(content)
    },

    // 处理文件选择
    handleFileSelect(event) {
      if (!this.enableMultimodal) return
      
      const files = Array.from(event.target.files)
      
      files.forEach(file => {
        // 检查文件大小 (限制20MB)
        if (file.size > 20 * 1024 * 1024) {
          alert(`文件 ${file.name} 超过20MB限制`)
          return
        }
        
        const fileObj = {
          name: file.name,
          type: file.type,
          size: file.size,
          isImage: file.type.startsWith('image/'),
          preview: null,
          file: file
        }
        
        // 读取文件预览
        const reader = new FileReader()
        reader.onload = (e) => {
          fileObj.preview = e.target.result
          this.selectedFiles.push(fileObj)
        }
        reader.readAsDataURL(file)
      })
    },

    // 删除文件
    removeFile(index) {
      this.selectedFiles.splice(index, 1)
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
    },

    // 复制消息内容
    copyMessage(content) {
      // 清除之前的定时器
      if (this.copyTimer) {
        clearTimeout(this.copyTimer)
      }

      // 复制到剪贴板
      if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(content)
          .then(() => {
            // 显示复制成功状态
            const index = this.messages.findIndex(msg => msg.content === content)
            this.copiedIndex = index
            
            // 2秒后恢复
            this.copyTimer = setTimeout(() => {
              this.copiedIndex = null
            }, 2000)
          })
          .catch(err => {
            console.error('复制失败:', err)
            this.fallbackCopy(content)
          })
      } else {
        // 降级方案
        this.fallbackCopy(content)
      }
    },

    // 降级复制方案
    fallbackCopy(content) {
      const textarea = document.createElement('textarea')
      textarea.value = content
      textarea.style.position = 'fixed'
      textarea.style.opacity = '0'
      document.body.appendChild(textarea)
      textarea.select()
      
      try {
        document.execCommand('copy')
        const index = this.messages.findIndex(msg => msg.content === content)
        this.copiedIndex = index
        
        this.copyTimer = setTimeout(() => {
          this.copiedIndex = null
        }, 2000)
      } catch (err) {
        console.error('降级复制失败:', err)
        alert('复制失败,请手动复制')
      }
      
      document.body.removeChild(textarea)
    },

    // 重新生成AI回复
    regenerateResponse(messageIndex) {
      // 找到对应的用户消息
      // 从当前消息向前查找最近的用户消息
      let userMessageIndex = -1
      for (let i = messageIndex - 1; i >= 0; i--) {
        if (this.messages[i].role === 'user') {
          userMessageIndex = i
          break
        }
      }

      if (userMessageIndex === -1) {
        console.error('未找到对应的用户消息')
        return
      }

      // 删除当前AI消息及之后的所有消息
      this.messages.splice(messageIndex)

      // 重新构建历史记录并发送请求
      const historyMessages = this.buildHistoryMessages()
      
      const chatParams = {
        model: 'zrt-multimodal-llm-8b',
        messages: historyMessages
      }

      console.log('重新生成,聊天参数:', JSON.stringify(chatParams, null, 2))

      // 发送AI请求
      this.sendAIRequest(chatParams)
    },

    // 打开图片合并弹框
    openMergeModal() {
      this.showMergeModal = true
      this.uploadedImages = []
      this.mergedImage = null
    },

    // 关闭图片合并弹框
    closeMergeModal() {
      this.showMergeModal = false
      this.uploadedImages = []
      this.mergedImage = null
    },

    // 处理图片上传
    handleImageUpload(event) {
      const files = Array.from(event.target.files)
      
      // 限制最多上传4张图片
      const remainingSlots = 4 - this.uploadedImages.length
      const filesToProcess = files.slice(0, remainingSlots)
      
      filesToProcess.forEach(file => {
        if (!file.type.startsWith('image/')) {
          alert('请选择图片文件')
          return
        }
        
        const reader = new FileReader()
        reader.onload = (e) => {
          this.uploadedImages.push({
            name: file.name,
            data: e.target.result
          })
        }
        reader.readAsDataURL(file)
      })
      
      // 清空input值以便可以重复上传相同文件
      event.target.value = ''
    },

    // 移除图片
    removeImage(index) {
      this.uploadedImages.splice(index, 1)
      this.mergedImage = null // 移除图片后清除合并结果
    },

    // 合并图片
    mergeImages() {
      if (this.uploadedImages.length < 2) {
        alert('至少需要上传2张图片才能合并')
        return
      }
      
      // 创建canvas用于合并图片
      const canvas = document.createElement('canvas')
      const ctx = canvas.getContext('2d')
      
      // 加载所有图片
      const imageElements = []
      let loadedCount = 0
      
      this.uploadedImages.forEach((imageData, index) => {
        const img = new Image()
        img.onload = () => {
          imageElements[index] = img
          loadedCount++
          
          // 所有图片加载完成后进行合并
          if (loadedCount === this.uploadedImages.length) {
            // 计算合并后图片的尺寸
            let totalWidth = 0
            let maxHeight = 0
            
            imageElements.forEach(img => {
              totalWidth += img.width
              if (img.height > maxHeight) {
                maxHeight = img.height
              }
            })
            
            // 设置canvas尺寸
            canvas.width = totalWidth
            canvas.height = maxHeight
            
            // 绘制所有图片
            let currentX = 0
            imageElements.forEach(img => {
              // 居中绘制图片
              const y = (maxHeight - img.height) / 2
              ctx.drawImage(img, currentX, y)
              currentX += img.width
            })
            
            // 获取合并后的base64数据
            this.mergedImage = canvas.toDataURL('image/png')
          }
        }
        img.src = imageData.data
      })
    },

    // 下载合并后的图片
    downloadMergedImage() {
      if (!this.mergedImage) return
      
      const link = document.createElement('a')
      link.href = this.mergedImage
      link.download = 'merged_image.png'
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
  }
}
</script>

<style scoped>
.chat-component {
  display: flex;
  flex-direction: column;
  height: 100%;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  overflow: hidden;
}

/* 消息区域 */
.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f7fa;
}

.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #cbd5e0;
  border-radius: 3px;
}

.message-wrapper {
  margin-bottom: 20px;
  display: flex;
}

.user-message {
  justify-content: flex-end;
}

.ai-message {
  justify-content: flex-start;
}

.message-content {
  display: flex;
  gap: 10px;
  max-width: 70%;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.message-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-bubble {
  padding: 12px 16px;
  border-radius: 12px;
  word-wrap: break-word;
}

.user-message .message-bubble {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-bottom-right-radius: 4px;
}

.ai-message .message-bubble {
  background: white;
  color: #2d3748;
  border-bottom-left-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.message-text {
  line-height: 1.6;
  white-space: pre-wrap;
}

/* Markdown渲染样式 */
.markdown-body {
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
}

.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
  margin-top: 16px;
  margin-bottom: 8px;
  font-weight: 600;
  line-height: 1.25;
}

.markdown-body h1 {
  font-size: 1.6em;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding-bottom: 4px;
}

.markdown-body h2 {
  font-size: 1.4em;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  padding-bottom: 4px;
}

.markdown-body h3 {
  font-size: 1.2em;
}

.markdown-body p {
  margin-bottom: 10px;
}

.markdown-body ul,
.markdown-body ol {
  margin-bottom: 10px;
  padding-left: 24px;
}

.markdown-body li {
  margin-bottom: 4px;
}

.markdown-body code {
  padding: 2px 6px;
  font-size: 85%;
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
}

.user-message .markdown-body code {
  background: rgba(255, 255, 255, 0.2);
  color: white;
}

.ai-message .markdown-body code {
  background: #f6f8fa;
  color: #e83e8c;
}

.markdown-body pre {
  padding: 12px;
  overflow: auto;
  font-size: 85%;
  line-height: 1.45;
  border-radius: 6px;
  margin-bottom: 10px;
  font-family: 'Monaco', 'Menlo', 'Consolas', monospace;
}

.user-message .markdown-body pre {
  background: rgba(0, 0, 0, 0.2);
}

.ai-message .markdown-body pre {
  background: #f6f8fa;
}

.markdown-body pre code {
  padding: 0;
  background: transparent;
  color: inherit;
}

.markdown-body blockquote {
  padding: 0 12px;
  margin: 10px 0;
  border-left: 3px solid;
}

.user-message .markdown-body blockquote {
  border-left-color: rgba(255, 255, 255, 0.5);
}

.ai-message .markdown-body blockquote {
  border-left-color: #dfe2e5;
  color: #6a737d;
}

.markdown-body table {
  border-collapse: collapse;
  margin-bottom: 10px;
  width: 100%;
}

.markdown-body table th,
.markdown-body table td {
  padding: 6px 12px;
  border: 1px solid;
}

.user-message .markdown-body table th,
.user-message .markdown-body table td {
  border-color: rgba(255, 255, 255, 0.3);
}

.ai-message .markdown-body table th,
.ai-message .markdown-body table td {
  border-color: #dfe2e5;
}

.markdown-body table th {
  font-weight: 600;
}

.user-message .markdown-body table th {
  background: rgba(255, 255, 255, 0.1);
}

.ai-message .markdown-body table th {
  background: #f6f8fa;
}

.markdown-body a {
  color: inherit;
  text-decoration: underline;
}

.markdown-body img {
  max-width: 100%;
  border-radius: 4px;
  margin: 8px 0;
}

.markdown-body hr {
  height: 0;
  margin: 15px 0;
  overflow: hidden;
  border: 0;
  border-bottom: 1px solid;
}

.user-message .markdown-body hr {
  border-bottom-color: rgba(255, 255, 255, 0.2);
}

.ai-message .markdown-body hr {
  border-bottom-color: #e1e4e8;
}

.markdown-body strong {
  font-weight: 600;
}

.markdown-body em {
  font-style: italic;
}

.message-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  gap: 8px;
  margin-top: 10px;
}

.image-item {
  position: relative;
  padding-top: 100%;
  overflow: hidden;
  border-radius: 8px;
  cursor: pointer;
}

.image-item img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.2s;
}

.image-item:hover img {
  transform: scale(1.05);
}

/* 消息中的文件列表 */
.message-files {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-top: 10px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border-radius: 8px;
  background: rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: background 0.2s;
}

.user-message .file-item {
  background: rgba(255, 255, 255, 0.2);
}

.file-item:hover {
  background: rgba(0, 0, 0, 0.08);
}

.user-message .file-item:hover {
  background: rgba(255, 255, 255, 0.3);
}

.file-item .file-icon {
  font-size: 24px;
  flex-shrink: 0;
}

.file-item .file-info {
  flex: 1;
  min-width: 0;
}

.file-item .file-name {
  font-size: 13px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-item .file-size {
  font-size: 11px;
  opacity: 0.7;
  margin-top: 2px;
}

/* 消息底部区域 */
.message-footer {
  display: flex;
  align-items: center;
  gap: 12px;
  padding-left: 4px;
}

.message-time {
  font-size: 11px;
  opacity: 0.6;
  color: #718096;
}

/* 消息操作按钮 */
.message-actions {
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.message-wrapper:hover .message-actions {
  opacity: 1;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 4px 10px;
  border: 1px solid #e2e8f0;
  background: #f7fafc;
  color: #4a5568;
  font-size: 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.action-btn:hover {
  background: #edf2f7;
  border-color: #cbd5e0;
  transform: translateY(-1px);
}

.action-btn span:first-child {
  font-size: 14px;
}

.btn-text {
  font-size: 12px;
}

.copy-btn.copied {
  background: #c6f6d5;
  border-color: #9ae6b4;
  color: #22543d;
}

.regenerate-btn:hover {
  background: #667eea;
  border-color: #667eea;
  color: white;
}

/* 输入中动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 16px !important;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #cbd5e0;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 输入区域 */
.chat-input-area {
  border-top: 1px solid #e2e8f0;
  background: white;
  padding: 16px;
}

/* 附件预览区域 */
.selected-files-preview {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.preview-file-item {
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e2e8f0;
  background: #f7fafc;
}

/* 图片预览 */
.preview-file-item.is-image {
  width: 80px;
  height: 80px;
}

.preview-file-item.is-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 文件预览 */
.preview-file-item:not(.is-image) {
  min-width: 200px;
  max-width: 250px;
}

.file-icon-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  gap: 4px;
}

.file-icon-wrapper .file-icon {
  font-size: 32px;
}

.file-icon-wrapper .file-name {
  font-size: 12px;
  color: #4a5568;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
}

.file-icon-wrapper .file-size {
  font-size: 10px;
  color: #a0aec0;
}

/* 删除按钮 */
.remove-file-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: none;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.remove-file-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.selected-images-preview {
  display: flex;
  gap: 10px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.preview-image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  border: 2px solid #e2e8f0;
}

.preview-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.remove-image-btn {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  border: none;
  background: rgba(0, 0, 0, 0.6);
  color: white;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
}

.remove-image-btn:hover {
  background: rgba(0, 0, 0, 0.8);
}

.input-controls {
  display: flex;
  gap: 10px;
  align-items: flex-end;
}

.upload-btn {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.upload-btn:hover {
  background: #edf2f7;
  border-color: #cbd5e0;
}

.upload-btn input {
  display: none;
}

.merge-images-btn {
  width: 42px;
  height: 42px;
  border-radius: 8px;
  background: #f7fafc;
  border: 1px solid #e2e8f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
  margin-right: 5px;
}

.merge-images-btn:hover {
  background: #edf2f7;
  border-color: #cbd5e0;
}

textarea {
  flex: 1;
  min-height: 42px;
  max-height: 120px;
  padding: 10px 14px;
  border: 1px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  font-family: inherit;
  resize: none;
  outline: none;
  transition: border-color 0.2s;
}

textarea:focus {
  border-color: #667eea;
}

.send-btn {
  padding: 0 24px;
  height: 42px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.send-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* 停止按钮 */
.stop-btn {
  padding: 0 24px;
  height: 42px;
  background: linear-gradient(135deg, #f56565 0%, #c53030 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  flex-shrink: 0;
}

.stop-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 101, 101, 0.4);
}

/* 图片预览模态框 */
.image-preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.9);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  cursor: pointer;
}

.preview-content {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.preview-content img {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
}

.close-preview-btn {
  position: absolute;
  top: -40px;
  right: 0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: none;
  background: white;
  color: #2d3748;
  font-size: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 图片合并弹框样式 */
.merge-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1001;
  padding: 20px;
}

.merge-modal-content {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  color: #2d3748;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #a0aec0;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.close-btn:hover {
  background: #f7fafc;
  color: #2d3748;
}

.modal-body {
  padding: 20px;
}

.upload-section {
  text-align: center;
  margin-bottom: 30px;
}

.upload-btn-large {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 30px;
  border: 2px dashed #cbd5e0;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s;
  background: #f7fafc;
  width: 100%;
}

.upload-btn-large:hover:not(.disabled) {
  border-color: #667eea;
  background: #edf2f7;
}

.upload-btn-large.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.upload-btn-large input {
  display: none;
}

.upload-btn-large span:first-child {
  font-size: 40px;
}

.upload-btn-large span:last-child {
  font-size: 16px;
  color: #4a5568;
}

.upload-info {
  margin-top: 15px;
  font-size: 14px;
  color: #718096;
}

.preview-section h4,
.result-section h4 {
  margin: 0 0 15px 0;
  font-size: 16px;
  color: #2d3748;
}

.image-previews {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.preview-item {
  position: relative;
  width: 120px;
  height: 120px;
  border-radius: 8px;
  overflow: hidden;
  border: 1px solid #e2e8f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-info {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  display: flex;
  justify-content: space-between;
  padding: 5px;
  background: rgba(0, 0, 0, 0.5);
}

.image-number {
  color: white;
  font-size: 12px;
  font-weight: bold;
}

.remove-btn {
  background: none;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.result-preview {
  text-align: center;
  padding: 20px;
  background: #f7fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.result-preview img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px;
  border-top: 1px solid #e2e8f0;
}

.merge-btn,
.download-btn {
  padding: 10px 24px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.merge-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.merge-btn:hover:not(:disabled) {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.merge-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.download-btn {
  background: #48bb78;
  color: white;
}

.download-btn:hover {
  background: #38a169;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.4);
}
</style>
